package cn.tedu.submarine;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

/**
 * 海洋对象类，所有对象的超类
 */
public abstract class SeaObject {

    public static final int LIVE = 0;
    public static final int DEAD = 1;
    /** 海洋对象类默认活着*/
    protected int state = LIVE;

    /** 高*/
    protected int height;
    /** 宽*/
    protected int width;
    /** x坐标*/
    protected int x;
    /** y坐标*/
    protected int y;
    /** 速度*/
    protected int speed;


    /**
     * 提供给侦察潜艇、鱼雷潜艇、水雷潜艇提供的构造方法
     */
    public SeaObject(int height, int width) {
        this.height = height;
        this.width = width;
        x = -width;
        Random rand = new Random(); //创建随机数对象
        y = rand.nextInt(World.HEIGHT-height-150+1)+150; //150到(窗口高-潜艇高)之内随机生成
        speed = rand.nextInt(3)+1; //1到3之内随机生成
    }

    /**
     * 提供给战舰、水雷、炸弹提供的构造方法
     */
    public SeaObject(int height, int width, int x, int y, int speed) {
        this.height = height;
        this.width = width;
        this.x = x;
        this.y = y;
        this.speed = speed;
    }


    /**
     * 移动
     */
    public abstract void move();

    /**
     * 判断对象是否是活着的
     * @return true表示活着
     */
    public boolean isLive(){
        return state==LIVE;
    }

    public boolean isDead(){
        return state==DEAD;
    }

    /**
     * 获取对象的图片
     * @return 返回对象所对应的图片
     */
    public abstract ImageIcon getImage();


    /**
     * 画对象
     * @param g 画笔
     */
    public void paintImage(Graphics g){
        if(this.isLive()){
            this.getImage().paintIcon(null,g,this.x,this.y);
        }
    }

    /**
     * 判断对象是否越界
     * @return: true表示越界
     */
    public boolean isOutOfBounds(){
        return this.x >= World.WIDTH;
    }

    /**
     * 判断碰撞
     * @return: true表示越界
     */
    public boolean isHit(SeaObject other){
        int x = other.x; //x代表炸弹的x
        int y = other.y; //y代表炸弹的y
        int x1 = this.x - other.width; //x1代表潜艇的x减去炸弹的宽
        int x2 = this.x + this.width; //x2代表潜艇的x加上潜艇的宽
        int y1 = this.y - other.height; //y1代表潜艇的y减去炸弹的高
        int y2 = this.y + this.height; //y2代表潜艇的y加上潜艇的高
        return x>=x1 && x<=x2 && y>=y1 && y<=y2;
    }

    public void goDead(){
        state = DEAD;
    }

}